import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor

from PyQt5 import QtWidgets, uic
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from UI.Ui_MainWindow import MainWindow
from UI.Ui_Progress import DProgress
import byzw


class App:
    def __init__(self):
        self.ui = MainWindow()
        # self.ui = uic.loadUi("UI/novel1.ui")
        self.initUI()
        self.books = []
        self.chapters = []
        self.progress = 0

    def initUI(self):
        with open("UI/BigSur_White.qss", "r") as f:
            qss = f.read()
        self.ui.setStyleSheet(qss)
        # self.ui.centralwidget.resize(600, 300)
        self.ui.book_list.setVisible(False)
        self.ui.btn_refresh.clicked.connect(self.refresh)
        self.ui.book_list.itemClicked.connect(self.jmp_book)
        self.ui.btn_jump.clicked.connect(self.locate_chapter)
        self.ui.btn_locate_page_1.clicked.connect(self.locate_page_1)
        # self.ui.chapter_list.itemClicked.connect(self.read_chapter)
        self.ui.btn_download_all.clicked.connect(self.download_all)

        self.timer = QTimer()
        self.timer.timeout.connect(self.update_value)

        # self.threadUpdate = UpdateValueThread()
        # self.threadUpdate.sig.connect(self.update_value)

    def update_value(self):
        # if num_files == len(self.chapters) - 1:
            # self.threadUpdate.stop()
        num_files = len(os.listdir())
        self.timer.start(500)
        self.ui.progress.setValue(num_files)

    def set_window_center(self, window):
        # 窗口居中
        screen = QDesktopWidget().screenGeometry()
        size = window.geometry()
        t = int((screen.height() - size.height()) / 2 - 40)
        l = int((screen.width() - size.width()) / 2)
        window.move(l, t)

    def test(self):
        print("Hello, world!")
        # print(self.ui.book_list.currentRow())

    def refresh(self):
        self.books = []
        self.ui.book_list.setVisible(True)
        #
        # self.set_window_center(self.ui.centralwidget)
        h = self.ui.btn_refresh.height() + self.ui.book_list.height() + 100
        self.ui.animation = QPropertyAnimation(self.ui.centralwidget, b'geometry')
        self.ui.animation.setDuration(500)
        self.ui.animation.setStartValue(QRect(self.ui.centralwidget.x(), self.ui.centralwidget.y(), 600, 150))
        self.ui.animation.setEndValue(QRect(self.ui.centralwidget.x(), self.ui.centralwidget.y(), 600, h))
        self.ui.animation.start()

        # self.ui.centralwidget.resize(600, h)
        self.ui.stackw_1.resize(600, h)

        surl = self.ui.combobox_surl.currentText()
        self.books = byzw.get_books(surl)
        if not self.books:
            return False
        for book in self.books:
            self.ui.book_list.addItem(book['title'])

    def jmp_book(self):
        self.chapters = []
        # print(self.ui.book_list.currentRow())
        self.ui.label2.setText(self.books[self.ui.book_list.currentRow()]['title'])

        burl = self.books[self.ui.book_list.currentRow()]['link']
        self.chapters = byzw.get_chapters(burl)

        for chapter in self.chapters:
            self.ui.chapter_list.addItem(chapter['title'])
        # time.sleep(1)
        # self.ui.centralwidget.resize(600, 600)
        # self.ui.stackw_1.resize(600, 600)

        # self.set_window_center(self.ui.centralwidget)
        self.ui.stackw_1.setCurrentIndex(1)
        self.ui.label3.setText('/' + str(len(self.chapters) - 1))

    def locate_chapter(self):
        row = int(self.ui.lineEdit_jump.text())
        if not row:
            QMessageBox.information(self.ui, u'提示', u'请先输入')
            return False
        if row > len(self.chapters):
            QMessageBox.information(self.ui, u'提示', u'超出范围')
            self.ui.lineEdit_jump.clear()
            return False
        item = self.ui.chapter_list.item(row)
        self.ui.chapter_list.scrollToItem(item)
        self.ui.lineEdit_jump.clear()

    def locate_page_1(self):
        self.chapters = []
        self.ui.chapter_list.clear()
        self.ui.stackw_1.setCurrentIndex(0)

    def download_all(self):
        dirname = self.ui.label2.text()
        if not os.path.exists(dirname):
            os.mkdir(dirname)
        os.chdir(dirname)
        self.ui.progress = QProgressDialog(u'下载进度', u'取消', 0, len(self.chapters), self.ui)
        self.ui.progress.setWindowTitle("下载中...")
        self.ui.progress.setWindowModality(Qt.WindowModal)
        self.ui.progress.show()
        # self.threadUpdate.start()
        indexs = [x for x in range(len(self.chapters))]
        with ThreadPoolExecutor(max_workers=8) as executor:
            executor.map(self.download, indexs)
        # for index in indexs:
        #     self.download(index)
        #     self.ui.progress.setValue(index)

        # self.ui.progress.setAutoClose(True)
        # for i in range(elapsed):
        #     self.ui.progress.setValue(i)
        #     time.sleep(0.02)
        #     QCoreApplication.processEvents()
        #     if self.ui.progress.wasCanceled():
        #         break
        # self.ui.progress.setValue(elapsed)

    def download(self, index):
        chapter = self.chapters[index]
        title = chapter['title']
        link = chapter['link']
        fname = title + '.txt'
        content = byzw.get_content(link).replace('<br>', '\n').replace('&nbsp;', ' ').replace('/p>', '')
        with open(fname, 'w') as f:
            f.write(title + '\n' + content)
        print("{}下载完成".format(title))

        # content = byzw.get_content(curl)

    #
    # def read_chapter(self):
    #     self.ui.textBrowser.clear()
    #     self.ui.stackw_1.setCurrentIndex(2)
    #
    #     screen = QDesktopWidget().screenGeometry()
    #     # self.ui.centralwidget.resize(screen.width(), screen.height())
    #     # self.ui.moveto(0, 0)
    #     self.ui.centralwidget.setGeometry(0, 0, 1680, 1050)
    #     self.ui.stackw_1.resize(1680, 1050)
    #     curl = self.chapters[self.ui.chapter_list.currentRow()]['link']
    #     ctitle = self.chapters[self.ui.chapter_list.currentRow()]['title']
    #     content = byzw.get_content(curl)
    #     self.ui.textBrowser.setText("<center>" + ctitle + "</center>")
    #     self.ui.textBrowser.append(content[0])
    #     self.ui.textBrowser.verticalScrollBar().setValue(0)


class UpdateValueThread(QThread):
    sig = pyqtSignal(int)

    def __init__(self):
        super(UpdateValueThread, self).__init__()

    def run(self):
        while True:
            num_files = len(os.listdir())
            print(num_files)
            time.sleep(0.5)
            self.sig.emit(num_files)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = App()
    form.ui.show()
    sys.exit(app.exec_())
